package com.tangding.hprose.api.server.command.impl.role;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.service.dao.user.UserRepository;
import com.tangding.service.entity.user.User;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月4日_上午10:58:16
 *
 */
@Component
public class PointRole2User implements Command{

	@Autowired
	UserRepository userRepository;
	
	@Override
	public Response exe(Object... params) throws GException {
		String selectedUid = JacksonUtil.get(params[0], "users.selectItem.key", true);
		Integer selectedRoleId = Integer.parseInt(JacksonUtil.get(params[0], "roles.selectItem.id", true));
		
		Map<String, User> userMap = userRepository.getUserMap();
		userMap.forEach((name, u) -> {
			Set<Integer> roles = u.getRoles();
			if (roles != null && roles.size() > 0) {
				if (roles.contains(selectedRoleId)) {
					roles.remove(selectedRoleId);
					try {
						userRepository.updateUser(u);
					} catch (GException e) {
						LogHelp.doLogException(e);
					}
					return;
				}
			}
		});
		
		User user = userRepository.getUserByUid(selectedUid);
		if (user != null) {
			Set<Integer> roles = user.getRoles();
			if (roles == null) {
				roles = new HashSet<Integer>();
			}
			roles.add(selectedRoleId);
			user.setRoles(roles);
		}
		userRepository.updateUser(user);
		return doResponseSucc();
	}
	
	public static void main(String[] args) {
		Set<Integer> sets = new HashSet<>();
		sets.add(1);
		sets.add(2);
		sets.add(3);
		sets.add(4);
		sets.add(5);
		if (sets.contains(4)) {
			sets.remove(4);
		}
		System.out.println(JacksonUtil.toJson(sets));
	}
}
